package pannel.cart;

import system.BasePage;
import pannel.user.User;
import pannel.order.Order;
import pannel.order.OrderDao;
import pannel.product.ProductDao;
import pannel.product.Product;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class CartPage extends BasePage {
    private DefaultTableModel model;
    private JTable table;
    private JLabel totalPriceLabel;
    private CartDao cartDao;
    private OrderDao orderDao;
    private ProductDao productDao;
    private double totalAmount = 0.0;

    public CartPage(User user) {
        super(user);
        cartDao = new CartDao();
        orderDao = new OrderDao();
        productDao = new ProductDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("购物车");
        setupContent();
        refreshTable();
    }

    private void setupContent() {
        contentArea.setLayout(new BorderLayout(10, 10));
        contentArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建表格
        String[] columnNames = {"商品图片", "商品名称", "单价", "数量", "小计", "操作", "cartId"};  // 添加隐藏的cartId列
        model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 3 || column == 5; // 只允许编辑数量和操作列
            }
        };
        
        table = new JTable(model);
        table.setRowHeight(100); // 设置行高以适应商品图片
        
        // 设置图片列渲染器
        table.getColumnModel().getColumn(0).setCellRenderer(new ImageRenderer());
        // 设置数量列编辑器
        table.getColumnModel().getColumn(3).setCellEditor(new QuantityEditor());
        // 设置操作列
        table.getColumnModel().getColumn(5).setCellRenderer(new ButtonRenderer());
        table.getColumnModel().getColumn(5).setCellEditor(new ButtonEditor());
        // 隐藏cartId列
        table.getColumnModel().getColumn(6).setMinWidth(0);
        table.getColumnModel().getColumn(6).setMaxWidth(0);
        table.getColumnModel().getColumn(6).setWidth(0);

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(scrollPane, BorderLayout.CENTER);

        // 底部面板
        JPanel bottomPanel = new JPanel(new BorderLayout());
        totalPriceLabel = new JLabel("总计: ￥0.00");
        totalPriceLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        
        JButton checkoutButton = new JButton("结算");
        checkoutButton.addActionListener(e -> handleCheckout());

        bottomPanel.add(totalPriceLabel, BorderLayout.WEST);
        bottomPanel.add(checkoutButton, BorderLayout.EAST);
        contentArea.add(bottomPanel, BorderLayout.SOUTH);
    }

    // 图片渲染器
    class ImageRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            JLabel label = new JLabel();
            if (value != null) {
                ImageIcon originalIcon = new ImageIcon(value.toString());
                Image image = originalIcon.getImage().getScaledInstance(80, 80, Image.SCALE_SMOOTH);
                label.setIcon(new ImageIcon(image));
            }
            label.setHorizontalAlignment(JLabel.CENTER);
            return label;
        }
    }

    // 数量编辑器
    class QuantityEditor extends DefaultCellEditor {
        private JSpinner spinner;
        private JPanel panel;

        public QuantityEditor() {
            super(new JTextField());
            spinner = new JSpinner(new SpinnerNumberModel(1, 1, 999, 1));
            panel = new JPanel(new BorderLayout());
            panel.add(spinner);
            
            spinner.addChangeListener(e -> {
                int row = table.getSelectedRow();
                if (row != -1) {
                    int cartId = (int) table.getValueAt(row, 6); // 隐藏的cartId列
                    int quantity = (int) spinner.getValue();
                    try {
                        cartDao.updateQuantity(cartId, quantity);
                        refreshTable();
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(CartPage.this, "更新数量失败：" + ex.getMessage());
                    }
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            spinner.setValue(value);
            return panel;
        }

        @Override
        public Object getCellEditorValue() {
            return spinner.getValue();
        }
    }

    // 按钮渲染器和编辑器
    class ButtonRenderer extends JButton implements javax.swing.table.TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            setText("删除");
            return this;
        }
    }

    class ButtonEditor extends DefaultCellEditor {
        private JButton button;
        private boolean isPushed;
        private int currentRow;

        public ButtonEditor() {
            super(new JTextField());
            button = new JButton();
            button.setOpaque(true);
            button.addActionListener(e -> {
                fireEditingStopped();
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            button.setText("删除");
            currentRow = row;
            isPushed = true;
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            if (isPushed) {
                try {
                    // 获取当前行的cartId
                    int cartId = Integer.parseInt(table.getModel().getValueAt(currentRow, 6).toString());
                    if (cartDao.delete(cartId)) {
                        SwingUtilities.invokeLater(() -> refreshTable());
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(CartPage.this, "删除失败：" + ex.getMessage());
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(CartPage.this, "删除操作出错：" + ex.getMessage());
                }
            }
            isPushed = false;
            return "删除";
        }

        @Override
        public boolean stopCellEditing() {
            isPushed = false;
            return super.stopCellEditing();
        }
    }

    private void refreshTable() {
        try {
            if (model == null || cartDao == null) {
                return;
            }

            List<Cart> carts = cartDao.queryByUser(getCurrentUser().getId());
            model.setRowCount(0);
            totalAmount = 0.0;

            for (Cart cart : carts) {
                model.addRow(new Object[]{
                    cart.getProductImage(),
                    cart.getProductName(),
                    String.format("￥%.2f", cart.getProductPrice()),
                    cart.getQuantity(),
                    String.format("￥%.2f", cart.getTotalPrice()),
                    "删除",
                    cart.getId() // 隐藏的cartId列
                });
                totalAmount += cart.getTotalPrice();
            }

            if (totalPriceLabel != null) {
                totalPriceLabel.setText(String.format("总计: ￥%.2f", totalAmount));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "获取购物车数据失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "发生错误：" + e.getMessage());
        }
    }

    private void handleCheckout() {
        int confirm = JOptionPane.showConfirmDialog(this, 
            String.format("确认结算？总金额：￥%.2f", totalAmount),
            "结算确认",
            JOptionPane.YES_NO_OPTION);
            
        if (confirm == JOptionPane.YES_OPTION) {
            try {
                List<Cart> carts = cartDao.queryByUser(getCurrentUser().getId());
                boolean allSuccess = true;
                
                for (Cart cart : carts) {
                    // 检查库存
                    Product product = productDao.getById(cart.getProductId());
                    if (product == null) {
                        JOptionPane.showMessageDialog(this, "商品不存在：" + cart.getProductName());
                        continue;
                    }
                    
                    if (product.getStock() < cart.getQuantity()) {
                        JOptionPane.showMessageDialog(this, 
                            String.format("商品 %s 库存不足，当前库存: %d", 
                                cart.getProductName(), 
                                product.getStock()));
                        allSuccess = false;
                        continue;
                    }

                    // 创建订单
                    Order order = Order.builder()
                            .userId(getCurrentUser().getId())
                            .productId(cart.getProductId())
                            .quantity(cart.getQuantity())
                            .totalPrice(cart.getTotalPrice())
                            .status(Order.STATUS_PENDING)
                            .createTime(new Date())
                            .build();
                            
                    if (orderDao.createOrder(order)) {
                        // 更新库存
                        product.setStock(product.getStock() - cart.getQuantity());
                        if (productDao.updateById(product)) {
                            // 删除购物车项
                            cartDao.delete(cart.getId());
                        } else {
                            allSuccess = false;
                            JOptionPane.showMessageDialog(this, 
                                "更新商品库存失败：" + cart.getProductName());
                        }
                    } else {
                        allSuccess = false;
                    }
                }
                
                if (allSuccess) {
                    JOptionPane.showMessageDialog(this, "结算成功！请前往订单页面支付");
                    refreshTable();
                } else {
                    JOptionPane.showMessageDialog(this, "部分订单创建失败，请重试");
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "结算失败：" + e.getMessage());
            }
        }
    }
} 